import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface Response<T> {
  data: T;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map((rawResponse) => {
        // 情况1：如果返回值已经是标准结构，直接透传
        if (
          typeof rawResponse === 'object' &&
          ('code' in rawResponse ||
            'message' in rawResponse ||
            'data' in rawResponse)
        ) {
          return {
            code: rawResponse.status ?? 0, // 默认状态码0
            message: rawResponse.message ?? 'success',
            data: rawResponse.data ?? null,
          };
        }

        // 情况2：普通返回值自动包装
        return {
          code: 0,
          message: 'success',
          data: rawResponse,
        };
      }),
    );
  }
}
